/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.github.zeleven.mua.utl;

import io.github.zeleven.mua.bean.FileBean;
import io.github.zeleven.mua.fraction.MainFraction;
import ohos.aafwk.ability.AbilitySlice;
import ohos.app.Environment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

/**
 * ReadFileUntils
 *
 * @since 2021-05-15
 */
public class ReadFileUntils {
    private static final int INT_1000 = 1000;
    private static final int INT_60 = 60;
    private static final int INT_24 = 24;

    /**
     * readFile
     *
     * @param list
     * @param slice
     * @return List
     */
    public static List<FileBean> readFile(List<FileBean> list, AbilitySlice slice) {
        list.clear();
        try {
            File file = slice.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
            BufferedReader in = null;
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                StringBuffer sb = new StringBuffer();
                File files1 = files[i];
                String name = files1.getName();
                long l = files1.lastModified();
                long millis = System.currentTimeMillis();
                int days = (int) ((l - millis) / (INT_1000 * INT_60 * INT_60 * INT_24));
                int hours = (int) ((l - millis) / (INT_1000 * INT_60 * INT_60));
                int minutes = (int) ((l - millis) / (INT_1000 * INT_60));
                String str = null;
                in = new BufferedReader(new FileReader(files1));
                while ((str = in.readLine()) != null) {
                    sb.append(str);
                }
                FileBean fileBean = new FileBean(name, sb.toString());
                list.add(fileBean);
            }
            return list;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            LogUtil.info(ReadFileUntils.class.getName(),"finally");
        }
        return null;
    }
}
